import dingtalkrobot_1_0, {
  BatchSendOTOHeaders,
  BatchSendOTORequest,
} from '@alicloud/dingtalk/dist/robot_1_0/client';
import Util, * as $Util from '@alicloud/tea-util';

import { DingClientService } from './client.serivce';

interface BatchSendOptions {
  robotCode: string;
  userIds: string[];
  msgKey: string;
  msgParam: string;
}
interface BatchSendHeader {
  accessToken: string;
}

export class DingRobotService extends DingClientService {
  constructor() {
    super();
  }

  private readonly client = new dingtalkrobot_1_0(this.createClient());

  /** 批量发送人与机器人会话中机器人消息
   *
   * @link https://open.dingtalk.com/document/orgapp/chatbots-send-one-on-one-chat-messages-in-batches
   */
  async batchSend(
    options: BatchSendOptions,
    headers: BatchSendHeader,
  ): Promise<void> {
    const batchSendOTOHeaders = new BatchSendOTOHeaders({
      xAcsDingtalkAccessToken: headers.accessToken,
    });

    const batchSendOTORequest = new BatchSendOTORequest({
      robotCode: options.robotCode,
      userIds: options.userIds,
      msgKey: options.msgKey,
      msgParam: options.msgParam,
    });
    try {
      const res = await this.client.batchSendOTOWithOptions(
        batchSendOTORequest,
        batchSendOTOHeaders,
        new $Util.RuntimeOptions({}),
      );
      if (res.statusCode !== 200) {
        throw new Error('发送卡片失败: ' + JSON.stringify(res.body));
      }
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        throw new Error(err.message);
      } else {
        throw new Error('发送卡片失败: ' + JSON.stringify(err));
      }
    }
  }
}
